package com.bsuir.avareader.textprocessing;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import android.content.Context;
import android.widget.TextView;

import com.bsuir.avareader.R;
import com.bsuir.avareader.dal.TextbookDbAdapter;

public class TxtHandler implements ITextHandler {
	private File textfile;
	private long readSize;
	private TextbookDbAdapter textbookAdapter;
	private Context mContext;

	public TxtHandler(Context context, String filename) {
		mContext = context;
		textfile = new File(filename);
		textbookAdapter = new TextbookDbAdapter(mContext);
		readSize = 0;
	}

	@Override
	public void parseTextbook(final TextView tv, int leftIndent, int rightIndent) {
		String line;
		int index = 0, counter;
		final int lIndent = leftIndent;
		final int rIndent = rightIndent;
		StringBuilder text = new StringBuilder("");
		
		textbookAdapter.open();

		try {
			BufferedReader br = new BufferedReader(new FileReader(textfile));
			while ((line = br.readLine()) != null) {
				final Bool bool = new Bool();
				String[] strArray = line.split(" ");
				text.append(strArray[0]);
				counter = 1;

				do {
					while (!bool.getIsTooLarge() && counter < strArray.length - 1) {
						final String txt = text.toString();
						tv.post(new Runnable() {
							public void run() {
								bool.setIsTooLarge(isTooLarge(tv, txt, lIndent, rIndent));
							}
						});
						text.append(" ").append(strArray[counter++]);
					}

					if (counter < strArray.length - 1) {
						textbookAdapter.insertLine(index++, text.toString());
						readSize += text.length();
						text = new StringBuilder("").append(strArray[counter++]);
					}
				} while (counter < strArray.length - 1);
			}
			br.close();
			textbookAdapter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public long getReadProgress() {
		return 100 * getReadSize() / getSize();
	}
	
	private boolean isTooLarge(TextView tv, String text, int lIndent, int rIndent) {
		float textWidth = tv.getPaint().measureText(text);
		return (textWidth + lIndent + rIndent >= tv.getMeasuredWidth());
	}

	private long getSize() {
		return 1;// (textfile != null) ? textfile.getTotalSpace() : -1;
	}
	
	private long getReadSize() {
		return readSize;
	}
	
	private class Bool {
		boolean isTooLarge = false;
		public boolean getIsTooLarge() {
			return isTooLarge;
		}
		public void setIsTooLarge(boolean isTooLarge) {
			this.isTooLarge = isTooLarge;
		}
	}
}